package com.chuangfeng.framework.core.common.util;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
	/**
	 * Logger for this class
	 */
	static final Logger logger = Logger.getLogger(StringUtil.class);

	/**
	 * 判断是否汉字
	 * 
	 * @param c
	 *            char 要判断的字符
	 * @return boolean
	 */
	public static boolean isChinese(char c) {
		String tmp = c + "";
		return tmp.matches("[\u4e00-\u9fa5]+");
	}

	/**
	 * 获得字符的低八位的值
	 * 
	 * @param c
	 *            char
	 * @return int
	 */
	public static int getLowBit(char c) {
		int intValue = (int) c;
		String hexValue = Integer.toHexString(intValue);
		int len = hexValue.length();
		if (len < 4) {
			for (int i = len; i < 4; i++) {
				hexValue = "0" + hexValue;
			}
		}
		hexValue = hexValue.substring(2, 4);

		return Integer.parseInt(hexValue, 16);
	}

	/**
	 * 获得字符的高八位的值
	 * 
	 * @param c
	 *            char
	 * @return int
	 */
	public static int getHighBit(char c) {
		int intValue = (int) c;
		String hexValue = Integer.toHexString(intValue);
		int len = hexValue.length();
		if (len < 4) {
			for (int i = len; i < 4; i++) {
				hexValue = "0" + hexValue;
			}
		}
		hexValue = hexValue.substring(0, 2);

		return Integer.parseInt(hexValue, 16);
	}

	/**
	 * 判断是否是一个整数串
	 * 
	 * @param value
	 *            String
	 * @return boolean
	 */
	public static boolean isInteger(String value) {
		boolean isInt = true;
		if ((value.startsWith("+")) || (value.startsWith("-"))) {
			value = value.substring(1);
		}
		for (int i = 0; i < value.length(); i++) {
			char ch = value.charAt(i);
			if (!Character.isDigit(ch)) {
				isInt = false;
				break;
			}// if
		}// for
		return isInt;
	}
	
	public static boolean isTelephoneNumber(String Telnumber){
		boolean isMobile = true;
		String regExp = "^1(3[0-9]|5[012789]|8[78])\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(Telnumber);
		if (m.find()) {
			isMobile = true;
		} else {
			isMobile = false;
		}
		return isMobile;
	}
	
	/**
	 * 判断是否为移动手机号码
	 * @param mobile
	 * @return
	 */
	public static boolean isChinaMobile(String mobile){
		boolean isMobile = true;
		String regExp = "^1(3[4-9]|5[012789]|8[278])\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(mobile);
		if (m.find()) {
			isMobile = true;
		} else {
			isMobile = false;
		}
		return isMobile;
	}
	
	/**
	 * 删除文本中的HTML标记
	 * 
	 * @param htmlText
	 *            String HTML文本
	 * @return String
	 */
	public static String removeHtmlTag(String htmlText) {
		String regex = "<.+?>";
		return htmlText.replaceAll(regex, "");
	}

	public static void main(String args[]) {
		String str = " <font color=red>aaa </font> bbb ";
		System.out.println(removeHtmlTag(str));
		
		System.out.println(filterString("[%,，\'\"/\\\\]*","adb\\ad"));
	}

	public static String turn(String str) {
		str = turnBracket(str);
		// 下面的代码将字符串以正确方式显示（包括回车，换行，空格）
		while (str.indexOf("\n") != -1) {
			str = str.substring(0, str.indexOf("\n")) + "<br/>"
					+ str.substring(str.indexOf("\n") + 1);
		}
		// while (str.indexOf(" ") != -1) {
		// str = str.substring(0, str.indexOf(" ")) + "&nbsp;"
		// + str.substring(str.indexOf(" ") + 1);
		// }
		str = turn1(str);
		return str;
	}

	private static String turn1(String str) {
		List<String> flag = new ArrayList<String>();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			Character c = str.charAt(i);
			if (c.equals('<')) {
				flag.add(c + "");
				sb.append(c);
			} else if (c.equals('>')) {
				flag.clear();
				sb.append(c);
			} else {
				if (flag.size() == 0) {// html标记外文本
					if (c.equals(' ')) {
						sb.append("&nbsp;");
					} else {
						sb.append(c);
					}
				} else {// html标记内文本
					sb.append(c);
				}
			}// if
		}// for
		return sb.toString();
	}

	// 将尖括号替换为转义字符
	public static String turnBracket(String str) {
		return str.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
	}

	public static String getMD5Str(String passwd) {

		try {
			byte[] res = passwd.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5".toUpperCase());
			byte[] hash = md.digest(res);
			StringBuffer d = new StringBuffer("");
			for (int i = 0; i < hash.length; i++) {
				int v = hash[i] & 0xFF;
				if (v < 16)
					d.append("0");
				d.append(Integer.toString(v, 16) + "");
			}
			return d.toString();
		} catch (Exception e) {
			return null;
		}
	}

	// 十进制转为十六进制
	public static String HexToStr(int i) {
		String s = "0123456789abcdef ";
		StringBuffer sb = new StringBuffer();
		for (int j = 0; i >= 16; j++) {
			int a = i % 16;
			i /= 16;
			sb.append(s.charAt(a));
		}
		sb.append(s.charAt(i));
		return sb.reverse().toString();
	}

	public static String toString(String[] arr, String separator) {
		String result = "";
		for (String el : arr) {
			result += el + separator;
		}
		if (result.endsWith(separator)) {
			result = result.substring(0, result.length() - separator.length());
		}
		return result;
	}

	/**
	 * 当 text 不为 null 且长度不为 0
	 * 
	 * @param text
	 *            String
	 * @return boolean
	 */
	public static boolean hasLength(String text) {
		return (text != null) && (text.length() > 0);
	}

	/**
	 * text 不能为 null 且必须至少包含一个非空格的字符
	 * 
	 * @param text
	 *            String
	 * @return boolean
	 */
	public static boolean hasText(String text) {
		return hasLength(text) && Pattern.matches(".*\\S.*", text);
	}
	/**
	 * 构造查询用的字符串
	 * @param strList
	 * @return
	 */
	public final static String getSqlStr(List<String> strList) {
		String str = "";
		if (strList != null && strList.size() > 0) {
			for (int i = 0; i < strList.size(); i++) {
				String s = strList.get(i);
				if (i != strList.size() - 1) {
					str = str + "'"+s+"',";
				}else{
					str = str + "'"+s+"'";
				}
			}
		}
		
		return str;
	}
	
	/**
	 * 过滤字符中特殊的字符串。导入用户资料的姓名里面的特殊字符串影响SQL查询
	 * @param regex
	 * @param str
	 * xiedy at 20100827
	 */
	public static String filterString(String regex,String str ){
		if(null==regex){
			return str;
		}else if(null==str){
			return null;
		}else{
			return str.replaceAll(regex, "");
		}
	}
	
	/**
	 * @param passLen生成密码的长度
	 * @return 生成由字母和数字组成的随机密码
	 * @throws WebException
	 */
	public static String getRandomPassword(Integer passLen){
		String password = "123456";
		final int  MAXNUM = 36;
		int count =0;// 生成密码的长度
		char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
			    'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
			    'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		StringBuffer pwd = new StringBuffer("");
		try {
			Random r = new Random();
			while (count < passLen) {
				int i = Math.abs(r.nextInt(MAXNUM)); // 生成的数最大为36-1
				if (i >= 0 && i < str.length) {
					pwd.append(str[i]);
					count++;
				}
			}
			password = pwd.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("获取随机密码异常："+e.getMessage());
		}
		return password;
	}
	
///////////////////////////////////////////////
	/**
	 * 是否有中文字符
	 * 
	 * @param s
	 * @return
	 */
	public static boolean hasCn(String s) {
		if (s == null) {
			return false;
		}
		return countCn(s) > s.length();
	}

	/**
	 * 获得字符。符合中文习惯。
	 * 
	 * @param s
	 * @param length
	 * @return
	 */
	public static String getCn(String s, int len) {
		if (s == null) {
			return s;
		}
		int sl = s.length();
		if (sl <= len) {
			return s;
		}
		// 留出一个位置用于…
		len -= 1;
		int maxCount = len * 2;
		int count = 0;
		int i = 0;
		while (count < maxCount && i < sl) {
			if (s.codePointAt(i) < 256) {
				count++;
			} else {
				count += 2;
			}
			i++;
		}
		if (count > maxCount) {
			i--;
		}
		return s.substring(0, i) + "…";
	}

	/**
	 * 计算GBK编码的字符串的字节数
	 * 
	 * @param s
	 * @return
	 */
	public static int countCn(String s) {
		if (s == null) {
			return 0;
		}
		int count = 0;
		for (int i = 0; i < s.length(); i++) {
			if (s.codePointAt(i) < 256) {
				count++;
			} else {
				count += 2;
			}
		}
		return count;
	}

	/**
	 * 文本转html
	 * 
	 * @param txt
	 * @return
	 */
	public static String txt2htm(String txt) {
		if (StringUtils.isBlank(txt)) {
			return txt;
		}
		StringBuilder sb = new StringBuilder((int) (txt.length() * 1.2));
		char c;
		for (int i = 0; i < txt.length(); i++) {
			c = txt.charAt(i);
			switch (c) {
			case '&':
				sb.append("&amp;");
				break;
			case '<':
				sb.append("&lt;");
				break;
			case '>':
				sb.append("&gt;");
				break;
			case '"':
				sb.append("&quot;");
				break;
			case ' ':
				sb.append("&nbsp;");
				break;
			case '\n':
				sb.append("<br/>");
				break;
			default:
				sb.append(c);
				break;
			}
		}
		return sb.toString();
	}

	/**
	 * html转文本
	 * 
	 * @param htm
	 * @return
	 */
	public static String htm2txt(String htm) {
		if (htm == null) {
			return htm;
		}
		htm = htm.replace("&amp;", "&");
		htm = htm.replace("&lt;", "<");
		htm = htm.replace("&gt;", ">");
		htm = htm.replace("&quot;", "\"");
		htm = htm.replace("&nbsp;", " ");
		htm = htm.replace("<br/>", "\n");
		return htm;
	}

	/**
	 * 替换字符串
	 * 
	 * @param sb
	 * @param what
	 * @param with
	 * @return
	 */
	public static StringBuilder replace(StringBuilder sb, String what,
			String with) {
		int pos = sb.indexOf(what);
		while (pos > -1) {
			sb.replace(pos, pos + what.length(), with);
			pos = sb.indexOf(what);
		}
		return sb;
	}

	/**
	 * 替换字符串
	 * 
	 * @param s
	 * @param what
	 * @param with
	 * @return
	 */
	public static String replace(String s, String what, String with) {
		return replace(new StringBuilder(s), what, with).toString();
	}

	/**
	 * 全角-->半角
	 * 
	 * @param qjStr
	 * @return
	 */
	public String Q2B(String qjStr) {
		String outStr = "";
		String Tstr = "";
		byte[] b = null;
		for (int i = 0; i < qjStr.length(); i++) {
			try {
				Tstr = qjStr.substring(i, i + 1);
				b = Tstr.getBytes("unicode");
			} catch (java.io.UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			if (b[3] == -1) {
				b[2] = (byte) (b[2] + 32);
				b[3] = 0;
				try {
					outStr = outStr + new String(b, "unicode");
				} catch (java.io.UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			} else
				outStr = outStr + Tstr;
		}
		return outStr;
	}

	public static final char[] N62_CHARS = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
			'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
			'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
			'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
			'X', 'Y', 'Z' };
	public static final char[] N36_CHARS = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
			'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
			'x', 'y', 'z' };

	private static StringBuilder longToNBuf(long l, char[] chars) {
		int upgrade = chars.length;
		StringBuilder result = new StringBuilder();
		int last;
		while (l > 0) {
			last = (int) (l % upgrade);
			result.append(chars[last]);
			l /= upgrade;
		}
		return result;
	}

	/**
	 * 长整数转换成N62
	 * 
	 * @param l
	 * @return
	 */
	public static String longToN62(long l) {
		return longToNBuf(l, N62_CHARS).reverse().toString();
	}

	public static String longToN36(long l) {
		return longToNBuf(l, N36_CHARS).reverse().toString();
	}

	/**
	 * 长整数转换成N62
	 * 
	 * @param l
	 * @param length
	 *            如N62不足length长度，则补足0。
	 * @return
	 */
	public static String longToN62(long l, int length) {
		StringBuilder sb = longToNBuf(l, N62_CHARS);
		for (int i = sb.length(); i < length; i++) {
			sb.append('0');
		}
		return sb.reverse().toString();
	}

	public static String longToN36(long l, int length) {
		StringBuilder sb = longToNBuf(l, N36_CHARS);
		for (int i = sb.length(); i < length; i++) {
			sb.append('0');
		}
		return sb.reverse().toString();
	}

	/**
	 * N62转换成整数
	 * 
	 * @param n62
	 * @return
	 */
	public static long n62ToLong(String n62) {
		return nToLong(n62, N62_CHARS);
	}

	public static long n36ToLong(String n36) {
		return nToLong(n36, N36_CHARS);
	}

	private static long nToLong(String s, char[] chars) {
		char[] nc = s.toCharArray();
		long result = 0;
		long pow = 1;
		for (int i = nc.length - 1; i >= 0; i--, pow *= chars.length) {
			int n = findNIndex(nc[i], chars);
			result += n * pow;
		}
		return result;
	}

	private static int findNIndex(char c, char[] chars) {
		for (int i = 0; i < chars.length; i++) {
			if (c == chars[i]) {
				return i;
			}
		}
		throw new RuntimeException("N62(N36)非法字符：" + c);
	}
	
}

